package com.ucode.springboot.starter.web.config;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
import cn.hutool.core.date.DateUtil;

/**
 * 默认的string to date的转化
 * @author: liliang
 * @date: 2019年12月17日 上午11:29:20
 */
public class StringToDateConverter implements Converter<String, Date> {


	@Override
	public Date convert(String value) {
		if (value == null || value.trim().length()==0) {
			return null;
		}
		value = value.trim();
		try {
			if (value.contains("-")) {
				return DateUtil.parse(value);
			} else if (value.matches("^\\d+$")) {
				Long lDate = new Long(value);
				return new Date(lDate);
			}
		} catch (Exception e) {
			if (value.contains("+") && value.length() == 24){
				SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
				return sdf.parse(value, new ParsePosition(0));
			}
			throw new RuntimeException(String.format("parser %s to Date fail", value));
		}
		throw new RuntimeException(String.format("parser %s to Date fail", value));
	}

}
